package com.ruoyi.ldzlsc.controller;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.ldzlsc.domain.ScWorkOrderTask;
import com.ruoyi.ldzlsc.domain.dto.WorkReportDto;
import com.ruoyi.ldzlsc.mapper.ScWorkOrderTaskMapper;
import com.ruoyi.ldzlsc.service.Impl.ScWorkReportServiceImpl;
import com.ruoyi.ldzlsc.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 质检结果回调控制器
 * 接收质检模块的回调通知
 * 
 * @author ldzl
 * @date 2025-01-23
 */
@RestController
@RequestMapping("/sc/quality-check")
public class QualityCheckCallbackController extends BaseController {


    @Autowired
    private ScWorkReportServiceImpl workReportService;
    
    @Autowired
    private WebSocketService webSocketService;
    
    @Autowired
    private ScWorkOrderTaskMapper workOrderTaskMapper;

    /**
     * 接收质检完成回调
     * 
     * @param callbackData 回调数据
     * @return 处理结果
     */
    @PostMapping("/callback")
    public AjaxResult receiveQualityCheckResult(@RequestBody Map<String, Object> callbackData) {
        try {
            System.out.println("=== 收到质检完成回调 ===");
            System.out.println("回调数据: " + callbackData);

            // 提取回调数据
            Long taskId = getLongFromMap(callbackData, "taskId");
            Long qualityCheckId = getLongFromMap(callbackData, "qualityCheckId");
            String checkResult = (String) callbackData.get("checkResult");
            BigDecimal qualifiedQty = getBigDecimalFromMap(callbackData, "qualifiedQty");
            BigDecimal unqualifiedQty = getBigDecimalFromMap(callbackData, "unqualifiedQty");
            String remarks = (String) callbackData.get("remarks");
            
            // 获取质检类型 - 检查是否是退料质检
            String sourceDocType = (String) callbackData.get("sourceDocType");
            String qualityCheckType = (String) callbackData.get("qualityCheckType");
            boolean isReturnMaterialQC = isReturnMaterialQualityCheck(sourceDocType, qualityCheckType);
            
            System.out.println("质检类型判断：sourceDocType=" + sourceDocType + 
                              ", qualityCheckType=" + qualityCheckType + 
                              ", 是否是退料质检=" + isReturnMaterialQC);

            // 验证必要参数
            if (taskId == null || qualityCheckId == null || checkResult == null || qualifiedQty == null) {
                return AjaxResult.error("回调数据不完整，缺少必要参数");
            }

            // 验证质检结果值
            if (!"1".equals(checkResult) && !"2".equals(checkResult) && !"3".equals(checkResult)) {
                return AjaxResult.error("质检结果值无效: " + checkResult);
            }

            System.out.println("处理质检回调 - 任务ID: " + taskId + ", 质检单ID: " + qualityCheckId + 
                             ", 结果: " + checkResult + ", 合格数量: " + qualifiedQty + 
                             ", 是否退料质检: " + isReturnMaterialQC);

            // 获取任务信息
            ScWorkOrderTask task = workOrderTaskMapper.selectScWorkOrderTaskByWorkOrderTaskId(taskId);
            if (task == null) {
                return AjaxResult.error("任务不存在，ID: " + taskId);
            }
            
            // 根据质检类型区分处理逻辑
            boolean isQualified = "1".equals(checkResult);
            if (isReturnMaterialQC) {
                // 如果是退料质检，先返回成功响应，避免Feign调用超时
                // 创建新线程处理耗时的入库操作
                final Long finalTaskId = taskId;
                final Long finalQualityCheckId = qualityCheckId;
                final boolean finalIsQualified = isQualified;
                final BigDecimal finalQualifiedQty = qualifiedQty;
                final BigDecimal finalUnqualifiedQty = unqualifiedQty;
                final String finalRemarks = remarks;

                // 在新线程中处理退料质检结果，避免阻塞响应
                new Thread(() -> {
                    try {
                        handleReturnMaterialQualityCheck(finalTaskId, finalQualityCheckId, finalIsQualified,
                                                       finalQualifiedQty, finalUnqualifiedQty, finalRemarks);
                    } catch (Exception e) {
                        System.err.println("后台处理退料质检结果异常: " + e.getMessage());
                        e.printStackTrace();
                    }
                }).start();

                return AjaxResult.success("退料质检结果处理成功");
            } else {
                // 如果是生产质检，检查任务状态是否为待质检
                if (!"5".equals(task.getStatus()) && !"3".equals(task.getStatus())) {
                    return AjaxResult.error("任务状态不是待质检或已完成，当前状态: " + task.getStatus());
                }
                
                // 创建报工数据对象
                WorkReportDto workReportDto = new WorkReportDto();
                workReportDto.setWorkOrderTaskId(taskId);
                workReportDto.setGoodQty(qualifiedQty);
                workReportDto.setScrapQty(unqualifiedQty != null ? unqualifiedQty : BigDecimal.ZERO);
                
                // 调用工作报告服务处理生产质检结果
                workReportService.handleQualityCheckResult(task, workReportDto, isQualified);
                return AjaxResult.success("生产质检结果处理成功");
            }

        } catch (Exception e) {
            System.err.println("处理质检结果回调异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("处理质检结果回调失败: " + e.getMessage());
        }
    }
    
    /**
     * 判断是否是退料质检
     * 
     * @param sourceDocType 源单据类型
     * @param qualityCheckType 质检类型
     * @return 是否是退料质检
     */
    private boolean isReturnMaterialQualityCheck(String sourceDocType, String qualityCheckType) {
        // 判断退料质检的条件（增加更详细的判断）：
        boolean isReturnQC = false;
        
        // 1. 质检类型为4 (RQC退料质检)
        if ("4".equals(qualityCheckType) || "RQC".equals(qualityCheckType)) {
            isReturnQC = true;
            System.out.println("根据质检类型确定为退料质检: " + qualityCheckType);
        }
        
        // 2. 或源单据类型为退料相关
        else if ("1".equals(sourceDocType)) {
            isReturnQC = true;
            System.out.println("根据源单据类型确定为退料质检: " + sourceDocType);
        }

        // 3. 或者源单据描述中包含"退料"
        else if (sourceDocType != null && sourceDocType.contains("退料")) {
            isReturnQC = true;
            System.out.println("根据源单据描述确定为退料质检，包含'退料'关键词");
        }

        
        return isReturnQC;
    }
    
    /**
     * 处理退料质检结果
     * 
     * @param taskId 任务ID
     * @param qualityCheckId 质检单ID
     * @param isQualified 是否合格
     * @param qualifiedQty 合格数量
     * @param unqualifiedQty 不合格数量
     * @param remarks 备注
     */
    private void handleReturnMaterialQualityCheck(Long taskId, Long qualityCheckId, boolean isQualified,
                                               BigDecimal qualifiedQty, BigDecimal unqualifiedQty, String remarks) {
        try {
            System.out.println("=== 处理退料质检结果 ===");
            System.out.println("任务ID: " + taskId);
            System.out.println("质检单ID: " + qualityCheckId);
            System.out.println("质检结果: " + (isQualified ? "合格" : "不合格"));
            System.out.println("合格数量: " + qualifiedQty);
            
            // 1. 发送WebSocket通知
            webSocketService.pushQualityCheckComplete(
                taskId,
                qualityCheckId,
                isQualified ? "1" : "2",
                "退料质检完成，结果: " + (isQualified ? "合格" : "不合格")
            );
            
//            // 2. 调用退料质检处理方法 - 与生产质检分开处理
//            workReportService.handleReturnMaterialQualityCheckResult(taskId, qualityCheckId, isQualified, qualifiedQty, unqualifiedQty);
//
        } catch (Exception e) {
            System.err.println("处理退料质检结果异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 接收质检进度回调
     * 
     * @param progressData 进度数据
     * @return 处理结果
     */
    @PostMapping("/progress")
    public AjaxResult receiveQualityCheckProgress(@RequestBody Map<String, Object> progressData) {
        try {
            System.out.println("=== 收到质检进度回调 ===");
            System.out.println("进度数据: " + progressData);

            // 提取进度数据
            Long taskId = getLongFromMap(progressData, "taskId");
            Long qualityCheckId = getLongFromMap(progressData, "qualityCheckId");
            String progress = (String) progressData.get("progress");
            String message = (String) progressData.get("message");

            // 验证必要参数
            if (taskId == null || progress == null) {
                return AjaxResult.error("进度数据不完整，缺少必要参数");
            }

            System.out.println("处理质检进度 - 任务ID: " + taskId + ", 质检单ID: " + qualityCheckId + 
                             ", 进度: " + progress + ", 消息: " + message);

            // 通过WebSocket推送进度更新
            webSocketService.pushQualityCheckProgress(taskId, qualityCheckId, progress, message);

            return AjaxResult.success("质检进度回调处理成功");

        } catch (Exception e) {
            System.err.println("处理质检进度回调异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("处理质检进度回调失败: " + e.getMessage());
        }
    }

    /**
     * 手动触发质检完成（用于测试）
     * 
     * @param taskId 任务ID
     * @param checkResult 质检结果
     * @param qualifiedQty 合格数量
     * @return 处理结果
     */
    @PostMapping("/manual-complete")
    public AjaxResult manualCompleteQualityCheck(@RequestParam Long taskId,
                                                @RequestParam String checkResult,
                                                @RequestParam BigDecimal qualifiedQty) {
        try {
            System.out.println("=== 手动触发质检完成 ===");
            System.out.println("任务ID: " + taskId + ", 结果: " + checkResult + ", 合格数量: " + qualifiedQty);

            // 模拟质检单ID
            Long qualityCheckId = System.currentTimeMillis();

            // 获取任务信息
            ScWorkOrderTask task = workOrderTaskMapper.selectScWorkOrderTaskByWorkOrderTaskId(taskId);
            if (task == null) {
                return AjaxResult.error("任务不存在，ID: " + taskId);
            }
            
            // 检查任务状态是否为待质检
            if (!"5".equals(task.getStatus())) {
                return AjaxResult.error("任务状态不是待质检，当前状态: " + task.getStatus());
            }
            
            // 创建报工数据对象
            WorkReportDto workReportDto = new WorkReportDto();
            workReportDto.setWorkOrderTaskId(taskId);
            workReportDto.setGoodQty(qualifiedQty);
            workReportDto.setScrapQty(BigDecimal.ZERO);
            
            // 直接调用工作报告服务处理质检结果
            boolean isQualified = "1".equals(checkResult);
            workReportService.handleQualityCheckResult(task, workReportDto, isQualified);

            return AjaxResult.success("手动质检完成处理成功");

        } catch (Exception e) {
            System.err.println("手动质检完成处理异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("手动质检完成处理失败: " + e.getMessage());
        }
    }

    /**
     * 获取健康检查接口
     */
    @GetMapping("/health")
    public AjaxResult healthCheck() {
        return AjaxResult.success("质检回调服务正常运行");
    }

    /**
     * 从Map中安全获取Long值
     */
    private Long getLongFromMap(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        if (value instanceof String) {
            try {
                return Long.parseLong((String) value);
            } catch (NumberFormatException e) {
                System.err.println("无法将字符串转换为Long: " + value);
                return null;
            }
        }
        return null;
    }

    /**
     * 从Map中安全获取BigDecimal值
     */
    private BigDecimal getBigDecimalFromMap(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        if (value instanceof Number) {
            return BigDecimal.valueOf(((Number) value).doubleValue());
        }
        if (value instanceof String) {
            try {
                return new BigDecimal((String) value);
            } catch (NumberFormatException e) {
                System.err.println("无法将字符串转换为BigDecimal: " + value);
                return null;
            }
        }
        return null;
    }
}
